<template>
  <div class="box">
    <!-- 头部组件模块 -->
    <MyHead></MyHead>
    <!-- 商品模块 -->
    <Cmd
      v-for="item in cartList"
      :key="item.id"
      :id="item.id"
      :imgscr="item.goods_img"
      :price1="item.goods_price * item.goods_count"
      :state1="item.goods_state"
      :init="item.goods_name"
      :count="item.goods_count"
      @stateChange="state"
      @addCount="changeCut"
      @addCount1="changeCut1"
      @count1="getPrice"
    ></Cmd>
    <!-- 结算模块 -->
    <div class="st">
      <MySt
        :state="fullState"
        :sunNum1="sunNum"
        :sunPrice1="sunPrice"
        @btnchange="getchange"

      ></MySt>
    </div>
  </div>
</template>

<script>
// 头部模块导入
import MyHead from "@/components/header.vue";
// 商品组件导入
import Cmd from "@/components/commodity.vue";
// 结算模块导入
import MySt from "@/components/settlement.vue";
// 导入 axios 库
import axios from "axios";
export default {
  components: {
    MyHead,
    Cmd,
    MySt,
  },
  data() {
    return {
      cartList: [],
    };
  },
  computed: {
    // 动态的计算 每一项是否被选中
    fullState() {
      return this.cartList.every((item) => item.goods_state);
    },
    // 计算商品价格
    sunPrice() {
      return this.cartList
        .filter((item) => item.goods_state)
        .reduce((sun, item) => (sun += item.goods_price * item.goods_count), 0);
    },
    // 商品的数量
    sunNum() {
      return this.cartList
        .filter((item) => item.goods_state)
        .reduce((sun, item) => (sun += item.goods_count), 0);
    },
  },
  methods: {
    // 请求列表数据
    async intCartList() {
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      //    console.log(res.list)
      // console.log(this)
      this.cartList = res.list;
      //   console.log(this.cartList);
    },
    // 接收子组件传过来的数据 将更新的数据 更改到 this.cartList
    state(val) {
      console.log(val);
      this.cartList.some((item) => {
        if (item.id == val.id) {
          item.goods_state = val.state;
          return true;
        }
      });
    },
    getchange(val) {
      // console.log(val);
      this.cartList.forEach((item) => {
        item.goods_state = val;
        // console.log('o')
      });
    },
    // 接收增加商品数量
    changeCut(val) {
      // console.log(val);
      this.cartList.some((item) => {
        // console.log('ok')
        if (item.id == val.id) {
          item.goods_count = val.count;
          // console.log('hellow')
          return true;
        }
      });
    },
    // 接收减少商品的数量
    changeCut1(val) {
      console.log(val);
      this.cartList.some((item) => {
        if (item.id == val.id) {
          item.goods_count = val.count;
          return true;
        }
      });
    },
    // 获取每个商品数量的价格
    getPrice(val) {
      console.log(val);
      console.log(this.cartList);
    },
  },
  created() {
    this.intCartList();
  },
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
.box {
  padding: 50px 0;
}
</style>
